package com.bjdd.jdy.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.route.BikingRouteLine;
import com.baidu.mapapi.search.route.BikingRoutePlanOption;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRoutePlanOption;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.IndoorRouteResult;
import com.baidu.mapapi.search.route.MassTransitRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.baidu.mapapi.utils.DistanceUtil;
import com.baidu.navisdk.adapter.BNRoutePlanNode;
import com.bjdd.jdy.Constant;
import com.bjdd.jdy.R;
import com.bjdd.jdy.baidu.LocationUtils;
import com.bjdd.jdy.baidu.NaviUtils;
import com.bjdd.jdy.base.RxManager;
import com.bjdd.jdy.entity.OrderBean;
import com.bjdd.jdy.entity.RoutePoint;
import com.bjdd.jdy.ui.map.MapActivity;
import com.bjdd.jdy.util.DateUtils;
import com.bjdd.jdy.util.JumpUtil;
import com.bjdd.jdy.util.L;
import com.bjdd.jdy.util.T;
import com.bjdd.jdy.view.other.MaterialProgressDrawable;
import com.zhy.autolayout.AutoLinearLayout;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2017/4/18.
 */

public class TakeOrderAdapter extends RecyclerView.Adapter {

    private Context mContext;
    private List<OrderBean> orders;
    private MaterialProgressDrawable progress;
    private boolean isMoreData = true;
    private RxManager rxManager = new RxManager();

    public TakeOrderAdapter(Context context, List<OrderBean> orderBeen) {
        this.mContext = context;
        this.orders = orderBeen;
        //this.orders.add((OrderBean) new Object());
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        MyViewHolder viewHolder;
        View view = LayoutInflater.from(mContext).inflate(R.layout.takeorder_item, null);
        viewHolder = new MyViewHolder(view);
        return viewHolder;

    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        MyViewHolder viewHolder = (MyViewHolder)holder;
        OrderBean orderBean = orders.get(position);
        viewHolder.tvShopType.setText(orderBean.getItem().getItemName());//物品类型
        viewHolder.tvOrderPrice.setText("￥"+orderBean.getCarrierShowMoney());//订单价格
        LatLng pointMe = new LatLng(LocationUtils.lat,LocationUtils.lng);
        L.d("我的位置："+LocationUtils.lng+"-------"+LocationUtils.lat);
        LatLng pointObject = new LatLng(orderBean.getConsignerLat(),orderBean.getConsignerLng());
        int distance = (int) (DistanceUtil.getDistance(pointMe,pointObject));
        String distanceMe = "";
        if (distance < 1000){
            distanceMe = "小于1km";
        }else {
            distanceMe = "小于" + (distance / 1000) + "km";
        }
        getDistance(viewHolder.tvDistanceMe,pointMe,pointObject);
        //viewHolder.tvDistanceMe.setText(distanceMe);
        viewHolder.tvDistanceShop.setText("大约"+(int)orderBean.getDistance()+"km");
        viewHolder.tvAddressSend.setText(orderBean.getReceiverAddress());
        viewHolder.tvAddressTake.setText(orderBean.getConsignerAddress());
        if (TextUtils.isEmpty(orderBean.getRemark()) || "".equals(orderBean.getRemark())){
            viewHolder.allRemark.setVisibility(View.GONE);
        }else {
            viewHolder.tvMark.setText(orderBean.getRemark());
        }
            /*long timeAll = 1*1000;
            long timeSpace = 1000;
            final CountDownTimer timer = new CountDownTimer(timeAll,timeSpace) {
                @Override
                public void onTick(long millisUntilFinished) {
                    viewHolder.btnTake.setText("接单（"+millisUntilFinished/timeSpace+"秒)");
                }

                @Override
                public void onFinish() {
                    viewHolder.btnTake.setText("接单");
                    orders.get(position).setTake(false);
                }
            };*/
        int type = orderBean.getOrderStatus();
        long t = 0;
        String s = "";
        if (type == Constant.ORDER_FINISH){
            t = orderBean.getFinishTime();
        }else {
            t = orderBean.getRequestTime();
        }
        s = DateUtils.formatDateTime(t);
        switch (type){

            case Constant.ORDER_PAID:
                if (orderBean.isAtOnce()){
                    viewHolder.tvOrderType.setText("及时取:"+s);
                }else {
                    viewHolder.tvOrderType.setText("预约取:"+s);
                }
                viewHolder.btnTake.setText("抢 单!");
                viewHolder.btnMap.setText("查看地图");
                break;
            case Constant.ORDER_PAIR:
                viewHolder.tvOrderType.setText("待取货:"+s);
                viewHolder.btnTake.setText("确认取货");
                viewHolder.btnMap.setText("地图导航");
                viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        JumpUtil.toOrderDetail(mContext,orderBean.getOrderNo());
                    }
                });
                break;
            case Constant.ORDER_SENDING:
                viewHolder.tvOrderType.setText("待配送:"+s);
                viewHolder.tvOrderType.setTextColor(mContext.getResources().getColor(R.color.light_blue));
                viewHolder.viewLineLeft.setBackgroundColor(mContext.getResources().getColor(R.color.light_blue));
                viewHolder.viewLineRight.setBackgroundColor(mContext.getResources().getColor(R.color.light_blue));
                viewHolder.btnTake.setText("确认收货");
                viewHolder.btnMap.setText("地图导航");
                viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        JumpUtil.toOrderDetail(mContext,orderBean.getOrderNo());
                    }
                });
                break;
            case Constant.ORDER_FINISH:
                viewHolder.tvOrderType.setText("已完成:"+s);
                viewHolder.tvOrderType.setTextColor(mContext.getResources().getColor(R.color.finish_time_text));
                viewHolder.viewLineLeft.setBackgroundColor(mContext.getResources().getColor(R.color.finish_time_text));
                viewHolder.viewLineRight.setBackgroundColor(mContext.getResources().getColor(R.color.finish_time_text));
                viewHolder.btnTake.setVisibility(View.GONE);
                viewHolder.btnMap.setText("查看详情");
                break;
            case Constant.ORDER_ERROR:
                viewHolder.tvOrderType.setText("订单异常:"+s);
                viewHolder.tvOrderType.setTextColor(mContext.getResources().getColor(R.color.finish_time_text));
                viewHolder.viewLineLeft.setBackgroundColor(mContext.getResources().getColor(R.color.finish_time_text));
                viewHolder.viewLineRight.setBackgroundColor(mContext.getResources().getColor(R.color.finish_time_text));
                viewHolder.btnTake.setVisibility(View.GONE);
                viewHolder.btnMap.setText("查看详情");
                break;
        }
        viewHolder.btnTake.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    /*if (orders.get(position).isTake()){
                        T.show("接单 ："+orders.get(position).getOrderId());
                        L.d("点击确认接单");
                        rxManager.post(Constant.GRAB,orders.get(position).getOrderId()+"");
                        orders.get(position).setTake(false);
                        viewHolder.btnTake.setText("接单");
                        //timer.cancel();
                    }else {
                        orders.get(position).setTake(true);
                        //timer.start();
                    }*/
                switch (type){
                    case Constant.ORDER_PAID:
                        //L.d("订单号：");
                        rxManager.post(Constant.GRAB,orders.get(position).getOrderId());
                        break;
                    case Constant.ORDER_PAIR:
                        JumpUtil.toInspection(mContext,orderBean.getOrderNo());
                        break;
                    case Constant.ORDER_SENDING:
                        if (orderBean.getPayType() == Constant.TO_PAY ){
                            JumpUtil.toPay(mContext,orderBean.getOrderNo(),orderBean.getReceiverLat(),orderBean.getReceiverLng());
                        }else {
                            JumpUtil.toSignScan(mContext,orderBean.getOrderNo()+"",orderBean.getOrderId()+"",orderBean.getReceiverLat(),orderBean.getReceiverLng());
                        }
                        break;
                    case Constant.ORDER_FINISH:

                        break;
                }
                //viewHolder.btnTake.setText("接单");
            }
        });
        viewHolder.btnMap.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RoutePoint point = new RoutePoint();
                point.setStartLat(LocationUtils.lat);
                point.setStartLng(LocationUtils.lng);
                point.setEndLat(orderBean.getReceiverLat());
                point.setEndLng(orderBean.getReceiverLng());
                switch (type){
                    case Constant.ORDER_PAID:
                        Intent intent = new Intent(mContext, MapActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable(Constant.POINTS,point);
                        intent.putExtras(bundle);
                        mContext.startActivity(intent);
                        break;
                    case Constant.ORDER_PAIR:
                        point.setEndLng(orderBean.getConsignerLng());
                        point.setEndLat(orderBean.getConsignerLat());
                        rxManager.post(Constant.NAV,point);
                        break;
                    case Constant.ORDER_SENDING:
                        rxManager.post(Constant.NAV,point);
                        break;
                    case Constant.ORDER_FINISH:
                        JumpUtil.toOrderDetail(mContext,orderBean.getOrderNo());
                        break;
                    case Constant.ORDER_ERROR:
                        JumpUtil.toOrderDetail(mContext,orderBean.getOrderNo());
                        break;
                }

            }
        });
    }

//    @Override
//    public void onBindViewHolder(MyViewHolder holder, int position) {
//
//    }

    private void noMoreData() {

    }


    @Override
    public int getItemCount() {
        return orders.size();
    }

    public boolean isMoreData() {
        return isMoreData;
    }

    public void setMoreData(boolean moreData) {
        isMoreData = moreData;
    }

    class MyViewHolder extends RecyclerView.ViewHolder {
        @Bind(R.id.tv_order_type)
        TextView tvOrderType;
        @Bind(R.id.tv_shop_type)
        TextView tvShopType;
        @Bind(R.id.tv_order_price)
        TextView tvOrderPrice;
        @Bind(R.id.tv_distance_me)
        TextView tvDistanceMe;
        @Bind(R.id.tv_distance_shop)
        TextView tvDistanceShop;
        @Bind(R.id.tv_address_take)
        TextView tvAddressTake;
        @Bind(R.id.tv_address_send)
        TextView tvAddressSend;
        @Bind(R.id.tv_mark)
        TextView tvMark;
        @Bind(R.id.btn_take)
        Button btnTake;
        @Bind(R.id.btn_map)
        Button btnMap;
        @Bind(R.id.ll_order_item)
        AutoLinearLayout llOrderItem;
        @Bind(R.id.all_remark)
        AutoLinearLayout allRemark;
        @Bind(R.id.top_line_left)
        View viewLineLeft;
        @Bind(R.id.top_line_right)
        View viewLineRight;
        public MyViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    class FooterViewHolder extends RecyclerView.ViewHolder {
        @Bind(R.id.img_loadmore)
        ImageView imgLoad;
        @Bind(R.id.rl_load_more)
        RelativeLayout view;

        public FooterViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    private void getDistance(TextView view,LatLng sNode,LatLng eNode){
        PlanNode stNode = PlanNode.withLocation(sNode);
        PlanNode enNode = PlanNode.withLocation(eNode);
        RoutePlanSearch search = RoutePlanSearch.newInstance();
        OnGetRoutePlanResultListener listener = new OnGetRoutePlanResultListener() {
            @Override
            public void onGetWalkingRouteResult(WalkingRouteResult walkingRouteResult) {

            }

            @Override
            public void onGetTransitRouteResult(TransitRouteResult transitRouteResult) {

            }

            @Override
            public void onGetMassTransitRouteResult(MassTransitRouteResult massTransitRouteResult) {

            }

            @Override
            public void onGetDrivingRouteResult(DrivingRouteResult drivingRouteResult) {
                if (drivingRouteResult != null){
                    int distance = drivingRouteResult.getRouteLines().get(0).getDuration();
                    //int distance = drivingRouteResult.getTaxiInfos().size();
                    String str = "大约";
                    if (distance < 1000 && distance > 0){
                        str += distance + "m";
                    }else if (distance <= 0){
                        str = "100米内";
                    }else {
                        str += (distance/1000) + "km";
                    }
//                str += drivingRouteResult.getRouteLines().size();
                    view.setText(str);
                }
                search.destroy();
            }

            @Override
            public void onGetIndoorRouteResult(IndoorRouteResult indoorRouteResult) {

            }

            @Override
            public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) {
                if (bikingRouteResult != null && bikingRouteResult.getRouteLines() != null && bikingRouteResult.getRouteLines().size() > 0){
                    int distance = bikingRouteResult.getRouteLines().get(0).getDuration();
                    distance = 0;
                    List<BikingRouteLine.BikingStep> data = bikingRouteResult.getRouteLines().get(0).getAllStep();
                    for (int i=0;i<data.size();i++){
                        distance += data.get(i).getDistance();
                    }
                    String str = "大约";
                    if (distance < 1000 && distance > 0){
                        str += distance + "m";
                    }else if (distance <= 0){
                        str = "100米内";
                    }else {
                        str += (distance/1000) + "km";
                    }
                    view.setText(str);
                }
            }
        };
        search.setOnGetRoutePlanResultListener(listener);
        /*search.drivingSearch(new DrivingRoutePlanOption()
        .from(stNode)
        .to(enNode));*/
        search.bikingSearch(new BikingRoutePlanOption()
        .from(stNode)
        .to(enNode));
    }
}
